package com.kevin.netty.demo.basic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty服务端基本使用
 */
public class NettyBasicServerExample {

    public static void main(String[] args) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(4);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                socketChannel.pipeline().addLast("h1",new NormalMessageHandler())
                                                        .addLast("h2", new ChannelInboundHandlerAdapter(){
                                                            @Override
                                                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                                                System.out.println("收到消息------------第二处理器");
                                                            }
                                                        });

                            }
                        });

        try {
            ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            System.out.println("Netty Server Started Success:listener port:8080");
            channelFuture.channel().closeFuture().sync();//同步等到服务端监听端口关闭
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }


}
